package com.luisliuyi.demo.optimize.network;

import android.util.Log;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

public class ConnectionPool {
    private Deque<HttpConnection> httpConnections = new ArrayDeque<>();

    public void putHttpConnection(HttpConnection httpConnection){
        httpConnections.add(httpConnection);
    }

    public synchronized HttpConnection getHttpConnection(String host, int port) {
        Iterator<HttpConnection> httpConnectionIterator = httpConnections.iterator();
        HttpConnection httpConnection = null;
        while(httpConnectionIterator.hasNext()){
            httpConnection = httpConnectionIterator.next();
            if (httpConnection.isSameAddress(host, port)) {
                httpConnectionIterator.remove();
                break;
            }
        }
        if (null == httpConnection) {
            httpConnection = new HttpConnection();
        } else {
            Log.d("liuyi", "从连接池中获得连接");
        }
        return httpConnection;
    }
}
